package quq.missq.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.photoselector.model.PhotoModel;
import java.util.ArrayList;
import quq.missq.R;
import quq.missq.utils.ImageLoadUtil;

/**
 * Created by River on 8/11/15.
 */
public class PublishTopicImageAdapter extends BaseAdapter{

    private Context mContext;
    private ArrayList<PhotoModel> mPhotoes;

    public PublishTopicImageAdapter(Context context){
        this.mContext = context;
    }

    public void setData(ArrayList<PhotoModel> photoes){
        this.mPhotoes = photoes;
    }

    public void addData(PhotoModel pPhoto){
        if(!isSame(pPhoto)){
            mPhotoes.add(pPhoto);
        }
    }

    public ArrayList<PhotoModel> getPhotoes(){
        return mPhotoes;
    }

    private boolean isSame(PhotoModel pPhoto){
        for (int i = 0; i < mPhotoes.size(); i++) {
            if (mPhotoes.get(i).getOriginalPath().equals(pPhoto.getOriginalPath())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getCount() {
        return mPhotoes.size();
    }

    @Override
    public Object getItem(int position) {
        return mPhotoes.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final PhotoModel photo = mPhotoes.get(position);
        Holder holder;
        if(convertView == null){
            holder = new Holder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.publish_topic_gridview_adapter,null);
            holder.imageView = (ImageView)convertView.findViewById(R.id.imageView);
            holder.deleteIcon = (ImageView)convertView.findViewById(R.id.deleteIcon);
            convertView.setTag(holder);
        }else{
            holder = (Holder)convertView.getTag();
        }
        ImageLoadUtil.loadImage(holder.imageView,"file:///"+photo.getOriginalPath(),R.mipmap.empty_photo);
        holder.deleteIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoes.remove(mPhotoes.get(position));
                PublishTopicImageAdapter.this.notifyDataSetChanged();
            }
        });
        return convertView;
    }

    public class Holder{
        public ImageView imageView;
        public ImageView deleteIcon;
    }

}
